<script setup>
import { ref, onMounted } from "vue";
import { useUserStore } from "@/stores/user";
import dayjs from "dayjs";
import { ElMessage } from "element-plus";
import axios from "axios";
import { serviceUrl } from "@/utils/request";

const userStore = useUserStore();

const userInfo = ref({
  username: "",
  describe: "",
  createdAt: "",
  updatedAt: "",
  avatarPath: "",
});

const isEditing = ref(false);
const editedProfile = ref({ ...userInfo.value });

onMounted(() => {
  userInfo.value = userStore.userInfo.record;
  console.log(userInfo.value);
});

const startEditing = () => {
  isEditing.value = true;
  editedProfile.value = { ...userInfo.value };
};

const updateUserProfile = async () => {
  try {
    const res = await axios.put("user/profile", editedProfile.value)
    if (res.data.code === 200) {
      ElMessage.success("修改成功");
      console.log(res.data.data);
      // userStore.updateUserInfo(res.data.data);

    }
  isEditing.value = false;
  }catch {
    ElMessage.error("更新失败");
  }


};

const file = ref(null);

const openFileDialog = () => {
  file.value.click();
};

const handleSelect = async (e) => {
  const file = e.target.files[0];
  if (!file) return;

  const form = new FormData();
  form.append("userId", userInfo.value.userId);
  form.append("file", file);

  try {
    const res = await axios.put(`/user/profile/avatar`, form);
    if (res.data.code === 200) {
      userStore.updateUserInfo({ avatarPath: res.data.data.filePath });
      console.log(userStore.userInfo);
      userInfo.value = userStore.userInfo;
      ElMessage.success("上传成功");
    } else {
      ElMessage.error("上传失败");
    }
  } catch {
    ElMessage.error("上传失败");
  }
  //
};

const cancelEditing = () => {
  isEditing.value = false;
};
</script>

<template>
  <el-card class="profile-page">
    <template #header>
      <div class="card-header">
        <el-text
          class="mx-1"
          style="font-size: 22px; font-weight: 600"
          v-if="!isEditing"
          >{{ userInfo.username }}</el-text
        >
        <el-input
          v-else
          v-model="editedProfile.username"
          style="font-size: 22px"
        />
      </div>
    </template>
    <div class="profile-detail">
      <div class="container-avatar">
        <el-image
          shape="square"
          fit="cover"
          :src="
            userInfo.avatarPath
              ? serviceUrl + userInfo.avatarPath
              : 'background.jpg'
          "
          :preview-src-list="['background.jpg']"
          class="profile-avatar"
        />
        <br />
        <input
          ref="file"
          type="file"
          accept="image/*"
          style="display: none"
          @change="handleSelect"
        />
        <el-button style="margin: auto" @click="openFileDialog"
          >上传头像</el-button
        >
      </div>

      <div>
        <el-text style="font-weight: 600; font-size: 18px"
          >个性签名：
          <el-text
            v-if="!isEditing"
            style="display: inline-block; font-size: 18px"
          >
            {{ userInfo.describe || "该用户暂无简介" }}
          </el-text>
          <el-text v-else style="display: inline-block; font-size: 18px">
            <el-input v-model="editedProfile.describe" />
          </el-text>
        </el-text>
        <el-text class="time-info">
          账号创建时间：{{
            dayjs(userInfo.createdAt).format("YYYY年MM月DD日 HH:mm")
          }}
        </el-text>
      </div>
    </div>

    <template #footer>
      <div class="actions" v-if="!isEditing">
        <button class="edit-profile-btn" @click="startEditing">
          编辑个人信息
        </button>
      </div>
      <div class="actions" v-else>
        <button class="save-btn" @click="updateUserProfile">保存</button>
        <button class="cancel-btn" @click="cancelEditing">取消</button>
      </div>
    </template>
  </el-card>
</template>

<style scoped>
.card-header {
  height: 20px;
  width: 100%;
}

.profile-page {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 30px;
  width: 800px;
  height: 550px;
  margin: 20px auto;
}

.profile-header {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
}
.profile-detail {
  width: 100%;
  height: 400px;
}

.edit-profile-btn {
  background-color: #646cff;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  font-size: 1rem;
  cursor: pointer;
  transition: background-color 0.3s;
}

.edit-profile-btn:hover {
  background-color: #535bf2;
}

.profile-avatar {
  width: 200px;
  height: 200px;
  border-radius: 5px;
  margin: auto;
}

.time-info {
  font-size: 18px;
  color: #999;
  margin-top: 10px;
  display: block;
}

.profile-details {
  margin-top: 20px;
}

.detail-item {
  margin-bottom: 10px;
}

.actions {
  display: flex;
  justify-content: space-evenly;
  flex-direction: row;
}

.container-avatar {
  display: flex;
  justify-content: flex-end;
  flex-direction: column;
  align-items: flex-end;
}

.save-btn,
.cancel-btn {
  padding: 10px 20px;
  border-radius: 4px;
  font-size: 1rem;
  cursor: pointer;
  border: none;
  width: 100px;
}

.save-btn {
  background-color: #646cff;
  color: white;
}

.cancel-btn {
  background-color: #f0f0f0;
  color: #333;
}

.save-btn:hover {
  background-color: #535bf2;
}

.cancel-btn:hover {
  background-color: #e0e0e0;
}
</style>
